<?php
/**
 *    我的运单列表控制器
 *    @author liangcajian QQ632324010
 */
define('NUM_PER_PAGE', 15); // 每页显示数量 

class My_kdorderApp extends MemberbaseApp
{
  function __construct()
  {
	  $this->My_kdorderApp();
  }
  
  function My_kdorderApp()
  {
	  parent::__construct();
	  $this->_kd_order =& m('kd_order');
	  $this->_kd_yubao_mod =& m('kd_yubao');
  }	
  function index()
  {
	  /* 搜索条件 */
	  $conditions = "order_alias.user_id = " . $this->visitor->get('user_id');
	  $page = $this->_get_page(NUM_PER_PAGE); 
	  $orders = $this->_kd_order->find(array(
		  'join'          => 'has_kdorderextm',
		  'fields'        => 'this.*,kd_orderextm.*',
		  'conditions'    => $conditions,
		  'limit'         => $page['limit'], //获取当前页的数据
		  'order'         => "addtime desc",
		  'count'         => true //允许统计
	  )); 

	  $page['item_count'] = $this->_kd_order->getCount(); //获取统计的数据
	  $this->_format_page($page);  
	  $this->assign('page_info', $page); //将分页信息传递给视图，用于形成分页条
	  $this->assign('orders', $orders);	 
	 
	  $this->assign('curitem', Lang::get('kdorder_list'));
	  $this->_config_seo('title', Lang::get('kdorder_list') . ' - ' . Lang::get('member_center'));
	  $this->display('my_kdorder.index.html');
  }

  /**
   *    添加
   *
   *    @author liangcajian QQ632324010
   *    @return    void
   */
  function add()
  {
	  if (!IS_POST)
	  {
		  $region_mod =& m('kd_fenlei');
		  $regions[0] = $region_mod->get_options(0);
		  $this->assign('regions', $regions);
		  
		  //服务项目
		  $m_kd_fuwu = &af('kd_fuwu');
		  $this->assign('fuwu_data', $m_kd_fuwu->getAll());

		  //快件物品
		  $m_kd_kuaidi = &af('kd_kuaidi');
		  $this->assign('kuaidi_data', $m_kd_kuaidi->getAll());
		  $order_info["goodswupin"] = array( 0 => array( 'yubao_id' => '0', 'PostOfficeID' => '','PostNumber' => '','GoodsName' => '','GoodsCount' => '0','GoodsWorth' => '0' ));
		  $this->assign('order_info', $order_info);
		
		  /* 四、填写发货地址、填写收货地址 */
		  $model_address =& m('address');
		  $addresses     = $model_address->find(array(
			  'conditions' => 'user_id = ' . $this->visitor->get('user_id'),
			  'order'      => 'case when default_use>0 then 0 else 1 end, default_use DESC, addr_id DESC',
		  ));
		  //设置一个系统自带的发货地址
		  $addresses[1] = array("addr_id" => "1","default_use" => "0","consignee" => $this->visitor->get('user_name'),"address" => "1619 s del mar ave san Gabriel ca91776",
		                        "zipcode" => "90001","phone_mob" => "626-566-7076","ddl_type" => "2","txt_countrys" => "USA//Los Angeles//Gabriel//","idpic" => "rbtnno");	
								//is_array($addresses) && sort($addresses);//数组排序 		  
		  foreach ($addresses as $key => $list){ $my_address[$list['ddl_type']][] = $list;}
		  $my_address_json = ecm_json_encode($addresses);
		  $this->assign('my_address_json', $my_address_json);
		  $this->assign('my_address', $my_address);
		  //print_r($addresses);
		
		  $this->assign('curitem', Lang::get('add_kdorder'));
		  $this->_config_seo('title', Lang::get('add_kdorder') . ' - ' . Lang::get('member_center'));
		  $this->import_resource(array('script' => 'abouts_kuaidi.js'));
		  $this->display('my_kdorder.form.html');			  
	  }
	  else
	  {
		//检查表单是否已正确填写了
		if ($this->check_form()==true){
		  
			//运单数据提交
			$data = $this->form_post_data();
			if (!$data){
				$this->show_warning("添加运单出错，请重新添加，或者联系管理员处理");
				return;
			}	
			//运单地址提交
			$data_address = $this->form_post_address($data);
            $this->show_message('add_ok',
				'back_list',    'index.php?app=my_kdorder',
				'continue_add', 'index.php?app=my_kdorder&amp;act=add'
             );			
		}
	  }
  }
  function edit()
  {
	  $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
	  if(!$order_id){
		  $this->show_warning('传入的ID为空，请重新操作'); return;
	  }	  
	  if (!IS_POST)
	  {
		  /* 获取订单信息 */
		  $order_info = $this->_kd_order->get(array(
			  'conditions' => " order_alias.order_id = {$order_id} and user_id = " . $this->visitor->get('user_id'),
			  'join'          => 'has_kdorderextm',//取出订单地址
		  ));
		  if(!$order_info){
			  $this->show_warning('没有找该运单信息'); return;
		  }
	   
		  //客户委托项目
		  $region_mod =& m('kd_fenlei');		  
		  $regions = array();//获每一个地区的父ID号出来
		  $date_parentid = $region_mod->find(array( 'conditions' => 'kd_fenlei.region_id' . db_create_in($order_info['xiangmu']) ));
		  foreach ($date_parentid as $key => $parentid){ $regions[] = $region_mod->get_options($parentid['parent_id']); }
		  if(!$regions){ $regions[0] = $region_mod->get_options(0); }
		  $this->assign('regions', $regions);
		  $choose_xiangmu = explode(",",$order_info['xiangmu']);
		  $this->assign('choose_xiangmu', $choose_xiangmu);	
		  
		  //二、快件物品
		  $m_kd_kuaidi = &af('kd_kuaidi');
		  $this->assign('kuaidi_data', $m_kd_kuaidi->getAll());
		  $order_info["goodswupin"] = $this->_kd_yubao_mod->find("order_id=".$order_info['order_id']); 
		  if(!$order_info["goodswupin"]){
		      $order_info["goodswupin"] = array( 0 => array( 'yubao_id' => '0','PostOfficeID' => '','PostNumber' => '','GoodsName' => '选择物品','GoodsCount' => '0','GoodsWorth' => '0' ));
		  }		  
		  
		  //三、选择服务项目
		  $m_kd_fuwu = &af('kd_fuwu');
		  $data_kd_fuwu = $m_kd_fuwu->getAll();
		  foreach ($data_kd_fuwu as $key => $fuwu){ if(strstr($order_info['ServiceItems'],''.$key.'')){ $data_kd_fuwu[$key]['check'] = $key; } }
		  $this->assign('fuwu_data', $data_kd_fuwu);
		  $ServiceItems['Fix'] = explode("//",$order_info['ServiceItemsFix']);
		  $ServiceItems['Bx'] = explode("//",$order_info['ServiceItemsBx']);
		  $this->assign('ServiceItems', $ServiceItems);
		  
		  //四、填写发货地址 五、填写收货地址
		  $countrys1 = explode('//',$order_info['txt_countrys']);
		  $order_info['txt_country'] = $countrys1[0];
		  $order_info['txt_province'] = $countrys1[1];
		  $order_info['txt_city'] = $countrys1[2];
		  $countrys = explode('//',$order_info['txtRece_countrys']);
		  $order_info['txtRece_country'] = $countrys[0];
		  $order_info['txtRece_province'] = $countrys[1];
		  $order_info['txtRece_city'] = $countrys[2];	
		  $order_info['txtqu'] = $countrys[3];		  
		  //json格式已有地址库
		  $model_address =& m('address');
		  $addresses     = $model_address->find(array(
			  'conditions' => 'user_id = ' . $this->visitor->get('user_id'),
			  'order'      => 'case when default_use>0 then 0 else 1 end, default_use DESC, addr_id',
		  )); 
		  //设置一个系统自带的发货地址
		  $addresses[1] = array("addr_id" => "1","default_use" => "0","consignee" => $this->visitor->get('user_name'),"address" => "1619 s del mar ave san Gabriel ca91776",
		                        "zipcode" => "90001","phone_mob" => "626-566-7076","ddl_type" => "2","txt_countrys" => "USA//Los Angeles//Gabriel//","idpic" => "rbtnno");	
								//is_array($addresses) && sort($addresses);//数组排序  
		  foreach ($addresses as $key => $list){ $my_address[$list['ddl_type']][] = $list;  }
		  $my_address_json = ecm_json_encode($addresses);
		  $this->assign('my_address_json', $my_address_json);
		  $this->assign('my_address', $my_address);
		  
		  //print_r($order_info);
		  $this->assign('order_info', $order_info);		
		
		  $this->assign('curitem', Lang::get('add_kdorder'));
		  $this->_config_seo('title', Lang::get('edit_kdorder') . ' - ' . Lang::get('member_center'));
		  $this->import_resource(array('script' => 'abouts_kuaidi.js'));
		  $this->display('my_kdorder.form.html');
	  }
	  else
	  {
		//检查表单是否已正确填写了
		if ($this->check_form()==true){
			//运单数据提交
			$data = $this->form_post_data($order_id);
			if (!$data){
				$this->show_warning("修改运单出错，请重新添加，或者联系管理员处理");
				return;
			}	
			//运单地址提交
			$data_address = $this->form_post_address($data);
			
            $this->show_message('edit_ok',
				'back_list',    'index.php?app=my_kdorder',
				'重新修改', 'index.php?app=my_kdorder&amp;act=edit&amp;order_id='.$order_id
             );			
		}	 
	  }
  }
  function view()
  {
	  $order_id = empty($_GET['order_id']) ? 0 : intval($_GET['order_id']);
	  /* 获取订单信息 */
	  $order_info = $this->_kd_order->get(array(
		  'conditions' => " order_alias.order_id = {$order_id} and user_id = " . $this->visitor->get('user_id'),
		  'join'          => 'has_kdorderextm',//取出订单地址
	  ));
	  if(!$order_info){
		  $this->show_warning('没有找该运单信息'); return;
	  }
	  
	  //二、快件物品
	  $order_info["goodswupin"] = $this->_kd_yubao_mod->find("order_id=".$order_info['order_id']); 
	  
	  //三、选择服务项目
	  $m_kd_fuwu = &af('kd_fuwu');
	  $data_kd_fuwu = $m_kd_fuwu->getAll();
	  foreach ($data_kd_fuwu as $key => $fuwu){ if(strstr($order_info['ServiceItems'],''.$key.'')){ $data_kd_fuwu[$key]['check'] = $key; } }
	  $this->assign('fuwu_data', $data_kd_fuwu);
	  $ServiceItems['Fix'] = explode("//",$order_info['ServiceItemsFix']);
	  $ServiceItems['Bx'] = explode("//",$order_info['ServiceItemsBx']);
	  $this->assign('ServiceItems', $ServiceItems);
	  $this->assign('order_info', $order_info);		

	  $this->assign('curitem', Lang::get('view_kdorder'));
	  $this->_config_seo('title', Lang::get('view_kdorder') . ' - ' . Lang::get('member_center'));
	  $this->display('my_kdorder.form.html');
  }  
  //表单所有项数据
  function form_post_data($order_id = 0)
  {
	//一、客户委托项目
	$date_xiangmu = $_POST['FromCountry'] ? $_POST['FromCountry'] .','.$_POST['ToCountry'] .','.$_POST['ExpressCompany'] .','.$_POST['TransportType'] : '';
	  
	//二、快件物品详情
	$yubao_data = array();
	if (is_array($_POST['GoodsName']) && count($_POST['GoodsName'])>0){
	  for ($i = 0; $i <count($_POST['GoodsName']);$i++){
		if (!empty($_POST['GoodsName'][$i])){
			$yubao_data[intval($_POST['yubao_id'][$i])] = array(
			   'yubao_id' => intval($_POST['yubao_id'][$i]),
			   'PostOfficeID' => trim($_POST['PostOfficeID'][$i]),
			   'yundanhao' => trim($_POST['PostNumber'][$i]),
			   'user_id' => $this->visitor->get('user_id'),
			   'user_name' => $this->visitor->get('user_name'),
			   'GoodsName' => trim($_POST['GoodsName'][$i]),
			   'GoodsCount' => intval($_POST['GoodsCount'][$i]),
			   'GoodsWorth' => intval($_POST['GoodsWorth'][$i]),
			   'updatetime' => time(),		
			);
			$goods_wupin[] = array('PostOfficeID' => trim($_POST['PostOfficeID'][$i]),'PostNumber' => trim($_POST['PostNumber'][$i]) );			
		}		  
	  }			
	}
	if($goods_wupin){ $data_goods_wupin = serialize($goods_wupin); }
	
	//三、选择服务项目
	$data_ServiceItems = $_POST['ServiceItems'] ? implode(",",$_POST['ServiceItems']) : '';
	if ($_POST['ServiceItemsFix']){ 
	   $data_ServiceItemsFix = intval($_POST['ServiceItemsFix']) .'//'. intval($_POST['SinglgFixAmount']) .'//'. $_POST['SingleFixMemo'];
	}
	if ($_POST['ServiceItemsBx']){ 
	   $data_ServiceItemsBx = intval($_POST['ServiceItemsBx']) .'//'. abs(floatval($_POST['ProtectAmount']));
	}	
	
	$data = array(
	  'xiangmu'        =>  $date_xiangmu,
	  'FaHuoDi'        =>  $_POST['FaHuoDi'],
	  'ShouHuoDi'      =>  $_POST['ShouHuoDi'],
	  'CangKuDiZhi'    =>  $_POST['CangKuDiZhi'],
	  'ZhuanYunFangShi'=>  $_POST['ZhuanYunFangShi'],
	  'Goods_wupin'    =>  $data_goods_wupin,
	  'SumGoodsAmount' =>  intval($_POST['SumGoodsAmount']),
	  'SumGoodsWorth'  =>  abs(floatval($_POST['SumGoodsWorth'])),
	  'ServiceItems'   =>  $data_ServiceItems,
	  'ServiceItemsFix'=> $data_ServiceItemsFix,
	  'ServiceItemsBx' =>  $data_ServiceItemsBx,
	  'Memo'           =>  trim($_POST['Memo']),
	  'updatetime'     =>  time(),
	);
	
	 /* 保存运单到数据表 */
	if ($order_id>0){	
        $this->_kd_order->edit($order_id, $data);
		if ($this->_kd_order->get_error()){
			$this->show_warning($this->_kd_order->get_error());
			return;
		}
		$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '修改快递运单,ID:'.$order_id, 0);//添加操作日志
		
		/* 如果快件物品详情不同了，把快件物品详情删除掉 */
		$yubao_diff = $this->_kd_yubao_mod->find(array( 'conditions' => "order_id = '{$order_id}'", 'fields' => 'yubao_id' ));
		$drop_yubao_ids = array_diff(array_keys($yubao_diff), array_keys($yubao_data));		
		if (!empty($drop_yubao_ids))
		{
			$this->_kd_yubao_mod->drop($drop_yubao_ids);
		}
						
	}
	else
	{
		$data['order_sn'] = $this->_gen_order_sn();
		$data['addtime'] = time();
		$data['user_id'] = $this->visitor->get('user_id');
		$data['user_name'] = $this->visitor->get('user_name');		
		$order_id = $this->_kd_order->add($data);
		if (!$order_id){
			$this->show_warning($this->_kd_order->get_error());
			return;
		}
		$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '添加快递运单,ID:'.$order_id, 0);//添加操作日志		
	}
	
	//二、添加/修改快件物品详情
	foreach ($yubao_data as $key => $yubao){
		$yubao['order_id'] = $order_id;
		if ($yubao['yubao_id']){
			$this->_kd_yubao_mod->edit($yubao['yubao_id'], $yubao);
		}else{
			$yubao['addtime'] = time();
			$this->_kd_yubao_mod->add($yubao);
		}
	}		
		  
	return $order_id;
  }

  //添加运单地址到运单地址表里
  function form_post_address($order_id = 0)
  {	 
	  //四、填写发货地址
	  $data = array(
		'order_id' =>  $order_id,//关联运单订单
		'txt_id' =>  htmldecode($_POST['address_options']),//id
		'txt_name' =>  htmldecode($_POST['txt_name']),//姓名
		'txt_mobilephone' =>  htmldecode($_POST['txt_mobilephone']),//手机电话
		'txt_countrys' =>  htmldecode($_POST['txt_country']).'//'.htmldecode($_POST['txt_province']).'//'.htmldecode($_POST['txt_city']),//国家/地区/省/市
		'txt_address' =>  htmldecode($_POST['txt_address']),//详细地址
		'txt_postoffice' =>  htmldecode($_POST['txt_postoffice']),//邮政
		'txtRece_id' =>  htmldecode($_POST['address_options1']),//id
		'txtRece_name' =>  htmldecode($_POST['txtRece_name']),//姓名
		//'txtRece_company' =>  htmldecode($_POST['txtRece_company']),//公司
		'txtRece_mobilephone' =>  htmldecode($_POST['txtRece_mobilephone']),//手机电话
		//'txtRece_email' =>  htmldecode($_POST['txtRece_email']),//邮箱地址
		'txtRece_countrys' =>  htmldecode($_POST['txtRece_country']).'//'.htmldecode($_POST['txtRece_province']).'//'.htmldecode($_POST['txtRece_city']).'//'.htmldecode($_POST['txtqu']),//国家/地区/省/市
		'txtRece_address' =>  htmldecode($_POST['txtRece_address']),//详细地址
		'idpic' =>  htmldecode($_POST['idpic']),//大陆非大陆
		'txtidcode' =>  htmldecode($_POST['txtidcode']),//身份证
		'txtRece_postoffice' =>  htmldecode($_POST['txtRece_postoffice']),//邮政
	  );
	    
	  /*  检查是否添加发货地址 ========================================================== */
	  $model_address =& m('address');
	  if (intval($_POST['address_options']) <= 0 && intval($_POST['save_address']) == 1)
	  {
		   $data_address = array(
			  'user_id'       => $this->visitor->get('user_id'),
			  'consignee'     => $data['txt_name'],//姓名
			  'phone_mob'     => $data['txt_mobilephone'],//手机电话
			  'txt_countrys'  => $data['txt_countrys'],//详细地址
			  'address'       => $data['txt_address'],//详细地址			  
			  'zipcode'       => $data['txt_postoffice'],//邮政
			  'ddl_type'     => 2,
			  'addtime'   => time(),
		  );
		  $txt_id = $model_address->add($data_address);
		  $txt_id && $data['txt_id'] = $txt_id;
	  }
	  /*  检查是否添加收货地址 ========================================================== */
	  if (intval($_POST['address_options1']) <= 0 && intval($_POST['save_address1']) == 1)
	  {
		   $data_address1 = array(
			  'user_id'       => $this->visitor->get('user_id'),
			  'consignee'     => $data['txtRece_name'],//姓名
			  'phone_mob'     => $data['txtRece_mobilephone'],//手机电话
			  'txt_countrys'  => $data['txtRece_countrys'],//详细地址
			  'address'       => $data['txtRece_address'],//详细地址
			  'idpic'         => $data['idpic'],//大陆非大陆
			  'txtidcode'     => $data['txtidcode'],//身份证			  
			  'zipcode'       => $data['txtRece_postoffice'],//邮政
			  'ddl_type'      => 1,
			  'addtime'   => time(),
		  );
		  $txtRece_id = $model_address->add($data_address1);
		  $txtRece_id && $data['txtRece_id'] = $txtRece_id;
	  }	
	  /*  检查是否添加收货人地址 ========================================================== */		 
	     
	  $mod_kd_order_extm =& m('kd_orderextm'); 
	  /* 保存运单地址到运单地址库里 */
	  if (intval($_POST['extm_id'])>0){	
		  $mod_kd_order_extm->edit(intval($_POST['extm_id']), $data);
	  }else{
		  $data1['add_time'] = time();
		  $mod_kd_order_extm->add($data);
	  }
	  if ($mod_kd_order_extm->get_error()){
		  $this->show_warning($mod_kd_order_extm->get_error());
		  return;
	  }
 		  
  }
  
  //检查表单的必填项
  function check_form()
  {  
	  if (!$_POST['FromCountry'] && !$_POST['FaHuoDi']){ $this->show_warning('请选择发货地'); return false; }
	  if (!$_POST['ToCountry'] && !$_POST['ShouHuoDi']){ $this->show_warning('请选择收货地'); return false; }
	  if (!$_POST['ExpressCompany'] && !$_POST['CangKuDiZhi']){ $this->show_warning('请选择所在仓库'); return false; }
	  if (!$_POST['TransportType'] && !$_POST['ZhuanYunFangShi']){ $this->show_warning('请选择转运方式'); return false; }
	  if (is_array($_POST['GoodsName']) && count($_POST['GoodsName'])>0){
	    for ($i = 0; $i <count($_POST['GoodsName']);$i++){
		  if (empty($_POST['GoodsName'][$i]) or $_POST['GoodsName'][$i]=="选择物品" ){ $this->show_warning('物品名不能为空'); return false; }
		  if (empty($_POST['GoodsCount'][$i]) or $_POST['GoodsCount'][$i]<=0 ){ $this->show_warning('物品数量不能为空且必须大于0'); return false; }
		  if (empty($_POST['GoodsCount'][$i]) or $_POST['GoodsCount'][$i]<=0 ){ $this->show_warning('物品价值不能为空且必须大于0'); return false; }
	    }			
	  }
	  if ($_POST['ServiceItemsFix']){ 
	     if (empty($_POST['SinglgFixAmount'])){ $this->show_warning('内部单件物品加固数量不能为空'); return false; }
		 if (empty($_POST['SingleFixMemo'])){ $this->show_warning('内部单件物品加固备注不能为空'); return false; }
	  }
	  if ($_POST['ServiceItemsBx']){ 
	     if (empty($_POST['ProtectAmount'])){ $this->show_warning('保价金额不能为空'); return false; }
	  }	  
	  if (empty($_POST['txt_name'])){ $this->show_warning('寄件人姓名不能为空'); return false; }
	  if (empty($_POST['txt_mobilephone'])){ $this->show_warning('寄件人手机/电话不能为空'); return false; }
	  if (empty($_POST['txt_country'])){ $this->show_warning('寄件人所在国家不能为空'); return false; }
	  if (empty($_POST['txt_city'])){ $this->show_warning('寄件人所在城市不能为空'); return false; }
	  if (empty($_POST['txt_address'])){ $this->show_warning('寄件人详细地址不能为空'); return false; }
	  if (empty($_POST['txtRece_name'])){ $this->show_warning('收件人姓名不能为空'); return false; }
	  if (empty($_POST['txtRece_mobilephone'])){ $this->show_warning('收件人手机/电话不能为空'); return false; }
	  if (empty($_POST['txtRece_country'])){ $this->show_warning('收件人所在国家不能为空'); return false; }
	  if (empty($_POST['txtRece_city'])){ $this->show_warning('收件人所在城市不能为空'); return false; }
	  if (empty($_POST['txtRece_address'])){ $this->show_warning('收件人详细地址不能为空'); return false; }
  
	  return true;
  }
  /** 生成订单号 @author liangcajian QQ632324010 */
  function _gen_order_sn()
  {
	  /* 选择一个随机的方案 */
	  mt_srand((double) microtime() * 1000000);
	  $timestamp = gmtime();
	  $y = date('y', $timestamp);
	  $z = date('z', $timestamp);
	  $order_sn = $y . str_pad($z, 3, '0', STR_PAD_LEFT) . str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
	  $model_order =& m('kd_order');
	  $orders = $model_order->find('order_sn=' . $order_sn);
	  if (empty($orders)){
		  return $order_sn;/* 否则就使用这个订单号 */
	  }
	  return $this->_gen_order_sn();/* 如果有重复的，则重新生成 */
  }
  
  //删除数据
  function drop()
  {
	  $id = isset($_GET['id']) ? htmldecode($_GET['id']) : '';
	  if (!$id)
	  {
		  $this->show_warning('请选择需要删除的记录');
		  return;
	  }
	  $this->_kd_order->drop("user_id = " .$this->visitor->get('user_id') . ' AND status = 0 AND ' . db_create_in($id,'order_id'));
	  $mod_kd_order_extm =& m('kd_orderextm'); 
	  $mod_kd_order_extm->drop(db_create_in($id,'order_id'));
	  $mod_yubao_extm =& m('kd_yubao'); 
	  $mod_yubao_extm->drop(db_create_in($id,'order_id'));	  
	  if ($this->_kd_order->has_error())
	  {
		  $this->show_warning($this->_kd_order->get_error());
		  return;
	  }
	  $this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '删除运单,ID:'.$id, 0);//添加操作日志

	  $this->show_message('drop_ok', 'back_list', 'index.php?app=my_kdorder' );	
  }
  //立即付款
  function payment()
  {
	  $order_id = isset($_GET['order_id']) ? $_GET['order_id'] : 0;
	  /* 获取订单信息 */
	  $order_info = $this->_kd_order->get(array(
		  'conditions' => " order_alias.order_id = {$order_id} AND order_alias.status = '3'  AND user_id = " . $this->visitor->get('user_id'),
	  ));
	  if(!$order_info){ $this->show_warning('该运单信息不存在 或者 不是待付款状态'); return; }
	  $order_total_amount = $order_info['totalfei'];
	  $my_money_mod =& m('my_money');
	  
	  if (!IS_POST)
	  {		
		$this->assign('order', $order_info);
		
		//print_r($order_info);
		
		//我的可用余额-------------------------------
		$my_money=$my_money_mod->getRow("select money,zf_pass from {$my_money_mod->table} where user_id='{$this->visitor->get('user_id')}'");	
		//判断我的可用余额是否足免来支付订单
		if( $my_money['money'] )//余额大于0者
		{
			if( $my_money['money'] >= $order_total_amount)
			{
				$my_money['balance_payment'] = 'ok';//您有足够的余额来支付订单，所以显示可用余额支付
			}else{
				$my_money['differ_amount'] = round($order_total_amount-$my_money['money'],2);//还差多少钱，使用网银充值
			}
		}
		$this->assign('my_money', $my_money);			
		$this->_config_seo('title', '请支付您的运单 - ' . Conf::get('site_title'));
		$this->display('my_kdorder.payment.html');
	  
	  }else{
			$password = isset($_POST['password']) ? $_POST['password'] : '';
			$order_id = isset($_POST['order_id']) ? $_POST['order_id'] : 0;
			if (empty($password)){ $this->show_warning('请输入支付密码'); return; }
			//读原始密码
			$my_money=$my_money_mod->getRow("select zf_pass,money from {$my_money_mod->table} where user_id='{$this->visitor->get('user_id')}'");
			if (empty($my_money['zf_pass'])){
				$this->show_warning('您还没设置支付密码，无法支付','设置支付密码','index.php?app=my_money&act=setpaypassword'); 
				return;	
			}	
			//转换32位 MD5
			$md5zf_password=md5($password);	
			if($md5zf_password != $my_money['zf_pass']){ $this->show_warning('支付密码错误，请重新输入'); return; }	
			//如果总金额为0元，则无法支付
			if ( $order_total_amount <= 0){ $this->show_warning('订单总金额小于等于0，无法支付'); return; }			
			if ($my_money['money'] < $order_total_amount){ $this->show_warning('您的帐户余额不足，无法支付订单'); return; }	
			
			//所有判断通过，可以更新订单和减少帐户余额了						
			$order_edit_array=array('money'=>$my_money['money']-$order_total_amount);
			$my_money_mod->edit('user_id='.$this->visitor->get('user_id'), $order_edit_array);
			//添加扣除金额的日志
			$log_text =$this->visitor->get('user_name').'余额支付运单'.$order['order_sn'].':'.$order_total_amount.Lang::get('yuan');
			$my_moneylog_mod =& m('my_moneylog');
			$my_moneylog_mod->add(array(
				'user_id'=>$this->visitor->get('user_id'),
				'user_name'=>$this->visitor->get('user_name'),
				'bank_name'=>'yue',//余额支付
				'add_time'=>gmtime(),
				'leixing'=>20, //订单支出	
				'caozuo'=>1, //状态已完成	
				'money'=>$order_total_amount,
				'money_yue'=>$order_edit_array['money'],//余额
				'log_text'=>$log_text,		
				's_and_z'=>2,//收入1,支出2	
			));	
			//通过检验，更新订单为已付款
			$ebank_type_check = Lang::get('ebank_type');//银行信息
			$this->_kd_order->edit($order_info['order_id'],array(
				'status'=> 5,//已付款，待发货的状态
				'pay_time' =>gmtime(),
			));	
			
			$this->write_log($this->visitor->get('user_id'), $this->visitor->get('user_name'), '支付快递运单,ID:'.$order_info['order_id'], 0);//添加操作日志
					
            $this->show_message('恭喜您支付成功', 'back_list', 'index.php?app=my_kdorder' );	
	  }
	  
  }

}
?>